from application import app, db
from web.models.user import Information, Group, User, Message, Association
from web.views.api import route_api
from flask import request, jsonify
from datetime import datetime


@route_api.route("/message/index", methods=['GET'])
def message_index():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if "user_id" in req else -1
    if user_id <= 0:
        resp['code'] = -1
        resp['msg'] = "操作错误"
        return jsonify(resp)

    messages = Message.query.filter_by(user_id=user_id, status=1).all()
    message_data_read_list = []
    message_data_unread_list = []
    for msg in messages:
        manager = User.query.filter_by(uid=msg.manager_id).first()
        item_data = {
            'id': msg.id,
            'title': msg.title,
            'content': msg.content,
            'created_time': str(msg.created_time),
            'is_read': msg.is_read,
            'manager_info': {
                'user_id': manager.uid,
                'nickname': manager.nickname,
                'avatar': manager.avatar
            },
            'group_info': {
                'group_id': -1,
                'name': '该群组已解散',
                'avatar': app.config['DEFAULT_AVATAR'],
            },
            'isfold': True,
        }
        group = Group.query.filter_by(gid=msg.gid, status=1).first()
        if group:
            item_data['group_info'] = {
                'group_id': group.gid,
                'name': group.name,
                'avatar': group.avatar,
            }
        if msg.is_read:
            message_data_read_list.append(item_data)
        else:
            message_data_unread_list.append(item_data)

    resp['data']['message_data_read_list'] = message_data_read_list[::-1]
    resp['data']['message_data_unread_list'] = message_data_unread_list[::-1]
    return jsonify(resp)


@route_api.route("/message/manager_index", methods=['GET'])
def manager_message_index():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    manager_id = int(req['manager_id']) if "manager_id" in req else -1
    manager_msg = Message.query.filter_by(user_id=manager_id, manager_id=manager_id, status=1).all()
    message_data_list = []
    for msg in manager_msg:
        item_data = {
            'user_id': msg.user_id,
            'manager_id': msg.manager_id,
            'group_id': msg.gid,
            'title': msg.title,
            'content': msg.content,
            'created_time': msg.created_time
        }
        message_data_list.append(item_data)

    resp['data']['message_data_list'] = message_data_list
    return jsonify(resp)


@route_api.route("/message/send", methods=['GET', 'POST'])
def send_message():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    manager_id = int(req['manager_id']) if "manager_id" in req else -1
    title = req['title'] if 'title' in req else ''
    content = req['content'] if 'content' in req else ''
    if manager_id <= 0:
        resp['code'] = -1
        resp['msg'] = "操作错误"
        return jsonify(resp)
    if not title or not content:
        resp['code'] = -1
        resp['msg'] = "标题或内容不能为空"
        return jsonify(resp)

    group_id_list = req['group_id_list'] if 'group_id_list' in req else ''
    # 获取发送的群组列表
    group_id_list = group_id_list.replace('[', '').replace(']', '').split(',')
    for id_str in group_id_list:
        if id_str:
            group_id = int(id_str)
            with db.auto_commit():
                manager_msg = Message(gid=group_id, title=title, content=content, manager_id=manager_id,
                                      user_id=manager_id, is_read=1, status=1, created_time=datetime.now())
                db.session.add(manager_msg)

                # 发送给群成员
                tar_ass_list = Association.query.filter_by(group_id=group_id, status=1).all()
                for tar_ass in tar_ass_list:
                    member_id = tar_ass.user_id
                    member_msg = Message(gid=group_id, title=title, content=content, manager_id=manager_id,
                                         user_id=member_id, is_read=0, status=1, created_time=datetime.now())
                    db.session.add(member_msg)

    return jsonify(resp)


@route_api.route("/message/message-read", methods=['GET'])
def read_message():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    msg_id = int(req['msg_id']) if 'msg_id' in req else -1
    with db.auto_commit():
        msg = Message.query.filter_by(id=msg_id, status=1).first()
        if not msg_id:
            resp['code'] = -1
            resp['msg'] = '消息已不存在'
            return jsonify(resp)
        msg.is_read = 1
        db.session.add(msg)

    return jsonify(resp)


@route_api.route("/message/message-delete", methods=['GET'])
def delete_message():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    msg_id = int(req['msg_id']) if 'msg_id' in req else -1
    with db.auto_commit():
        msg = Message.query.filter_by(id=msg_id, status=1).first()
        if not msg:
            resp['code'] = -1
            resp['msg'] = '消息已不存在'
            return jsonify(resp)
        msg.status = 0
        db.session.add(msg)

    return jsonify(resp)


@route_api.route("/message/information-index")
def get_information():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    user_id = int(req["user_id"]) if "user_id" in req else -1
    if user_id <= 0:
        resp["code"] = -1
        resp["msg"] = "操作错误"
        return jsonify(resp)

    # 获取消息数据
    inf_list = Information.query.filter_by(user_id=user_id, status=1).all()
    inf_data_list = []
    if inf_list:
        for inf_item in inf_list:
            group_id = inf_item.group_id
            tar_group = Group.query.filter_by(gid=group_id).first()
            if not tar_group:
                continue

            manager_id = inf_item.manager_id
            member_id = inf_item.member_id
            if not manager_id or not member_id:
                continue

            manager = User.query.filter_by(uid=manager_id).first()
            member = User.query.filter_by(uid=member_id).first()
            item_data = {
                'id': inf_item.id,
                'group_info': {
                    'gid': group_id,
                    'name': tar_group.name,
                },
                'manager_info': {
                    'uid': manager_id,
                    'nickname': manager.nickname,
                    'avatar': manager.avatar
                },
                'user_info': {
                    'uid': member_id,
                    'nickname': member.nickname,
                    'avatar': member.avatar
                },
                'is_read': inf_item.is_read,
                'created_time': inf_item.created_time,
                'inform_type': inf_item.inform_type,
                'done_type': inf_item.done_type,
                'is_manager': inf_item.is_manager
            }

            inf_data_list.append(item_data)

    resp['data']['inf_data_list'] = inf_data_list
    return jsonify(resp)


@route_api.route("/message/information-read")
def read_information():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    inf_id = req['id_list'] if 'id_list' in req else 'null'
    if inf_id == 'null':
        resp['code'] = -1
        resp['msg'] = '消息不存在'
        return jsonify(resp)
    inf_id = int(inf_id)
    with db.auto_commit():
        inf = Information.query.filter_by(id=inf_id).first()
        inf.is_read = 1
        db.session.add(inf)

    return jsonify(resp)


@route_api.route("/message/information-remove")
def remove_information():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    inf_id_list = req['id_list'] if 'id_list' in req else ''
    str_id_list = inf_id_list.replace('[', '').replace(']', '').split(',')
    for id_str in str_id_list:
        if id_str:
            inf_id = int(id_str)
            with db.auto_commit():
                inf = Information.query.filter_by(id=inf_id).first()
                if not inf:
                    continue
                inf.status = 0
                db.session.add(inf)

    return jsonify(resp)


@route_api.route("/message/information-count")
def get_information_count():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if 'user_id' in req else -1
    count = Information.query.filter_by(user_id=user_id, is_read=0, status=1).count()
    resp['data'] = {'count': count}
    return jsonify(resp)
